package by.averianov.discounta.dataaccess.impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.averianov.discounta.dataaccess.UserAccountDao;
import by.averianov.discounta.datamodel.UserAccount;
import by.averianov.discounta.datamodel.UserAccount_;

@Repository
public class UserAccountDaoImpl extends AbstractDaoImpl<Long, UserAccount> implements UserAccountDao {

    protected UserAccountDaoImpl() {
        super(UserAccount.class);
    }
    
    @Override
	public List<UserAccount> getAllAccountOrderId() {
    	CriteriaBuilder cb = getEm().getCriteriaBuilder();
		CriteriaQuery<UserAccount> query = cb.createQuery(UserAccount.class);
				
		Root<UserAccount> root = query.from(UserAccount.class);
		query.orderBy(cb.asc(root.get("id")));

		TypedQuery<UserAccount> q = getEm().createQuery(query);
		List<UserAccount> list = q.getResultList();
		return list;
	}
    
    @Override
    public void setUserStatus(Boolean status, Long id) {
    	UserAccount user = getById(id);
    	user.setUserStatus(status);
    	update(user);
    }
    
    @Override
	public UserAccount getByEmail(String email) {
    	CriteriaBuilder cb = getEm().getCriteriaBuilder();

		CriteriaQuery<UserAccount> criteria = cb.createQuery(UserAccount.class);
        Root<UserAccount> root = criteria.from(UserAccount.class);

        criteria.select(root);
        criteria.where(cb.equal(root.get(UserAccount_.userEmail), email));

        TypedQuery<UserAccount> query = getEm().createQuery(criteria);
        UserAccount results = query.getSingleResult();
        return results;
    }
}
